<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>大数据职称考试答题工具</title>
    <style>
        :root {
            --primary-color: #1e88e5;
            --primary-light: #42a5f5;
            --primary-dark: #1565c0;
            --bg-color: #f8f9fa;
            --card-bg: #ffffff;
            --text-primary: #2c3e50;
            --text-secondary: #6c757d;
            --border-color: #e9ecef;
            --success: #4caf50;
            --error: #f44336;
            --option-bg: #f8f9ff;
            --option-hover: #e3f2fd;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-primary);
            line-height: 1.6;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 800px;
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(30, 136, 229, 0.1);
            overflow: hidden;
            touch-action: manipulation;
        }

        .header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            margin: 0;
            font-size: 1.4rem;
            font-weight: 500;
        }

        .header p {
            margin: 8px 0 0 0;
            font-size: 0.85rem;
            opacity: 0.9;
        }

        .select-container {
            padding: 40px;
            text-align: center;
        }

        .select-title {
            font-size: 1.1rem;
            margin-bottom: 20px;
            color: var(--text-primary);
        }

        .exam-options {
            display: flex;
            flex-direction: column;
            gap: 16px;
            margin-bottom: 30px;
        }

        .exam-option {
            padding: 16px;
            background-color: var(--option-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            text-align: left;
        }

        .exam-option:hover {
            background-color: var(--option-hover);
            transform: translateY(-1px);
        }

        .exam-option.selected {
            background-color: rgba(30, 136, 229, 0.1);
            border-color: var(--primary-color);
            position: relative;
        }

        .exam-option.selected::after {
            content: '✓';
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            font-weight: bold;
            color: var(--primary-color);
        }

        .exam-option-title {
            font-weight: 600;
            margin-bottom: 4px;
            color: var(--text-primary);
        }

        .exam-option-desc {
            font-size: 0.85rem;
            color: var(--text-secondary);
        }

        .start-btn {
            padding: 14px 24px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
            width: 200px;
        }

        .start-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .start-btn:hover:not(:disabled) {
            background-color: var(--primary-dark);
        }

        .question-container {
            padding: 24px;
            display: none;
        }

        .question-stem {
            font-size: 1.1rem;
            line-height: 1.6;
            margin-bottom: 20px;
            color: var(--text-primary);
            font-weight: 500;
        }

        .options {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-bottom: 20px;
        }

        .option {
            display: flex;
            align-items: center;
            padding: 14px 16px;
            background-color: var(--option-bg);
            border: 1px solid var(--border-color));
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 1rem;
            user-select: none;
        }

        .option:hover {
            background-color: var(--option-hover);
            transform: translateY(-1px);
        }

        .option.selected {
            background-color: rgba(30, 136, 229, 0.1);
            border-color: var(--primary-color);
            position: relative;
        }

        .option.selected::after {
            content: '✓';
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            font-weight: bold;
            color: var(--primary-color);
        }

        .option.correct {
            background-color: rgba(76, 175, 80, 0.1);
            border-color: var(--success);
            color: var(--success);
        }

        .option.incorrect {
            background-color: rgba(244, 67, 53, 0.1);
            border-color: var(--error);
            color: var(--error);
        }

        .option-letter {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background-color: var(--primary-color);
            color: white;
            border-radius: 50%;
            margin-right: 10px;
            font-weight: 600;
            font-size: 0.8rem;
        }

        .feedback {
            text-align: center;
            font-size: 1rem;
            font-weight: 600;
            margin: 16px 0;
            padding: 12px;
            border-radius: 8px;
            opacity: 0;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: opacity 0.3s ease;
        }

        .feedback.show {
            opacity: 1;
        }

        .feedback.correct {
            background-color: rgba(76, 175, 80, 0.1);
            color: var(--success);
            border: 1px solid rgba(76, 175, 80, 0.3);
        }

        .feedback.incorrect {
            background-color: rgba(244, 67, 53, 0.1);
            color: var(--error);
            border: 1px solid rgba(244, 67, 53, 0.3);
        }

        .action-btns {
            display: flex;
            gap: 12px;
            margin-top: 16px;
        }

        .btn {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background-color: var(--primary-dark);
        }

        .btn-primary:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
        }

        .btn-outline:hover {
            background-color: var(--option-hover);
        }

        .ai-explanation {
            margin-top: 20px;
            padding: 16px;
            background-color: #f8f9ff;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            font-size: 0.95rem;
            line-height: 1.6;
            display: none;
        }

        .ai-explanation h4 {
            margin: 0 0 12px 0;
            color: var(--primary-color);
            font-weight: 600;
            font-size: 1rem;
        }

        .ai-explanation p {
            margin: 8px 0;
            color: var(--text-primary);
        }

        .ai-explanation.loading {
            text-align: center;
            color: var(--text-secondary);
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: var(--text-secondary);
            font-size: 0.9rem;
        }

        .stats {
            text-align: center;
            color: var(--text-secondary);
            padding: 12px;
            background-color: var(--bg-color);
            border-top: 1px solid var(--border-color));
            font-size: 0.85rem;
        }

        .nav-buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
            padding: 10px;
            background-color: var(--bg-color);
            border-top: 1px solid var(--border-color);
        }

        .nav-btn {
            padding: 8px 16px;
            border: 1px solid var(--primary-color);
            background-color: white;
            color: var(--primary-color);
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        .nav-btn:hover {
            background-color: var(--primary-color);
            color: white;
        }

        .nav-btn.active {
            background-color: var(--primary-color);
            color: white;
        }

        .error-list-container {
            padding: 20px;
            display: none;
        }

        .error-list-header {
            font-size: 1.2rem;
            margin-bottom: 15px;
            color: var(--text-primary);
            text-align: center;
            padding: 10px 0;
            border-bottom: 1px solid var(--border-color);
        }

        .error-item {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-bottom: 12px;
            padding: 16px;
        }

        .error-item-stem {
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--text-primary);
        }

        .error-item-options {
            font-size: 0.95rem;
            color: var(--text-secondary);
            margin-bottom: 8px;
        }

        .error-item-answer {
            font-size: 0.9rem;
            color: var(--success);
            margin-bottom: 8px;
        }

        .error-item-actions {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
        }

        .error-btn {
            padding: 6px 12px;
            font-size: 0.85rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .error-btn-practice {
            background-color: var(--primary-color);
            color: white;
        }

        .error-btn-remove {
            background-color: #f44336;
            color: white;
        }

        @media (max-width: 480px) {
            .container {
                border-radius: 8px;
                margin: 10px;
            }

            .header h1 {
                font-size: 1.2rem;
            }

            .select-container,
            .question-container {
                padding: 20px;
            }

            .question-stem {
                font-size: 1rem;
            }

            .exam-option {
                padding: 14px;
            }

            .action-btns {
                flex-direction: column;
            }

            .btn {
                padding: 14px;
            }

            .stats {
                font-size: 0.8rem;
                padding: 10px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>大数据职称考试答题工具</h1>
        <p>随机练习 · 持续学习</p>
    </div>

    <!-- 选择题库界面 -->
    <div class="select-container" id="selectContainer">
        <h2 class="select-title">请选择练习题库</h2>
        <div class="exam-options">
            <div class="exam-option" data-file="./data.json" id="option1">
                <div class="exam-option-title">大数据分析应用高级职称</div>
                <div class="exam-option-desc">包含数据分析、数据挖掘、统计学等专业知识</div>
            </div>
            <div class="exam-option" data-file="./data1.json" id="option2">
                <div class="exam-option-title">大数据系统研发高级职称</div>
                <div class="exam-option-desc">包含系统开发、软件工程、架构设计等专业知识</div>
            </div>
        </div>
        <button class="start-btn" id="startBtn" disabled>开始练习</button>
    </div>

    <!-- 答题界面 -->
    <div class="question-container" id="questionContainer">
        <div class="loading" id="loading">正在加载题库...</div>
    </div>

    <!-- 错题库界面 -->
    <div class="error-list-container" id="errorListContainer">
        <div class="error-list-header">错题本（共 <span id="errorCount">0</span> 道）</div>
        <div id="errorList"></div>
    </div>

    <!-- 底部导航 -->
    <div class="nav-buttons">
        <button class="nav-btn active" id="navPractice">练习模式</button>
        <button class="nav-btn" id="navError">错题本</button>
    </div>

    <div class="stats">
        <span>已答：<span id="answeredCount">0</span></span> |
        <span>正确：<span id="correctCount">0</span></span> |
        <span>正确率：<span id="accuracyRate">0%</span></span>
    </div>
</div>

<script>
    // 统计数据
    let answeredCount = 0;
    let correctCount = 0;
    let currentQuestion = null;
    let selectedOptions = [];
    let currentQuestionBank = null;
    let selectedExamFile = null;
    let errorQuestions = []; // 错题库

    // 阿里云百炼API配置
    const API_KEY = 'sk-ffd09133e1914047ac016e39165895af';
    const API_ENDPOINT = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';

    // DOM元素
    const selectContainer = document.getElementById('selectContainer');
    const questionContainer = document.getElementById('questionContainer');
    const errorListContainer = document.getElementById('errorListContainer');
    const loadingElement = document.getElementById('loading');
    const answeredElement = document.getElementById('answeredCount');
    const correctElement = document.getElementById('correctCount');
    const accuracyElement = document.getElementById('accuracyRate');
    const startBtn = document.getElementById('startBtn');
    const examOptions = document.querySelectorAll('.exam-option');
    const navPractice = document.getElementById('navPractice');
    const navError = document.getElementById('navError');
    const errorList = document.getElementById('errorList');
    const errorCount = document.getElementById('errorCount');

    // 从 localStorage 加载错题
    function loadErrorQuestions() {
        const saved = localStorage.getItem('errorQuestions');
        if (saved) {
            try {
                errorQuestions = JSON.parse(saved);
            } catch (e) {
                errorQuestions = [];
            }
        }
        updateErrorCount();
    }

    // 保存错题到 localStorage
    function saveErrorQuestions() {
        localStorage.setItem('errorQuestions', JSON.stringify(errorQuestions));
        updateErrorCount();
    }

    // 更新错题数量显示
    function updateErrorCount() {
        errorCount.textContent = errorQuestions.length;
    }

    // 添加错题
    function addErrorQuestion(question) {
        // 检查是否已存在
        if (!errorQuestions.some(q => q.stem === question.stem)) {
            errorQuestions.push(JSON.parse(JSON.stringify(question))); // 深拷贝
            saveErrorQuestions();
            renderErrorList();
        }
    }

    // 移除错题
    function removeErrorQuestion(stem) {
        errorQuestions = errorQuestions.filter(q => q.stem !== stem);
        saveErrorQuestions();
        renderErrorList();
    }

    // 错题被答对后移除
    function markErrorCorrect(stem) {
        removeErrorQuestion(stem);
    }

    // 渲染错题列表
    function renderErrorList() {
        errorList.innerHTML = '';
        if (errorQuestions.length === 0) {
            errorList.innerHTML = '<p style="text-align:center;color:var(--text-secondary);padding:20px;">暂无错题</p>';
            return;
        }
        errorQuestions.forEach(q => {
            const item = document.createElement('div');
            item.className = 'error-item';
            const optionsText = q.options ? q.options.map(opt => opt.substring(2)).join(', ') : '';
            const answerText = Array.isArray(q.answer) ? q.answer.join(', ') : q.answer;
            item.innerHTML = `
                <div class="error-item-stem">${q.stem}</div>
                <div class="error-item-options">${optionsText}</div>
                <div class="error-item-answer">正确答案：${answerText}</div>
                <div class="error-item-actions">
                    <button class="error-btn error-btn-practice" data-stem="${encodeURIComponent(q.stem)}">重练此题</button>
                    <button class="error-btn error-btn-remove" data-stem="${encodeURIComponent(q.stem)}">移除</button>
                </div>
            `;
            errorList.appendChild(item);
        });

        // 绑定按钮事件
        document.querySelectorAll('.error-btn-practice').forEach(btn => {
            btn.addEventListener('click', function() {
                const stem = decodeURIComponent(this.getAttribute('data-stem'));
                const q = errorQuestions.find(q => q.stem === stem);
                if (q) {
                    showQuestionInPracticeMode(q);
                }
            });
        });

        document.querySelectorAll('.error-btn-remove').forEach(btn => {
            btn.addEventListener('click', function() {
                const stem = decodeURIComponent(this.getAttribute('data-stem'));
                removeErrorQuestion(stem);
            });
        });
    }

    // 在练习模式中显示指定题目
    function showQuestionInPracticeMode(question) {
        // 切换到练习界面
        selectContainer.style.display = 'none';
        errorListContainer.style.display = 'none';
        questionContainer.style.display = 'block';
        navPractice.classList.add('active');
        navError.classList.remove('active');

        // 清除 loading 并渲染题目
        if (loadingElement) loadingElement.style.display = 'none';
        renderQuestion(question);
        currentQuestion.isErrorPractice = true;
    }

    // 选择题库
    examOptions.forEach(option => {
        option.addEventListener('click', () => {
            examOptions.forEach(opt => opt.classList.remove('selected'));
            option.classList.add('selected');
            selectedExamFile = option.getAttribute('data-file');
            startBtn.disabled = false;
        });
    });

    // 开始练习
    startBtn.addEventListener('click', () => {
        if (!selectedExamFile) return;
        selectContainer.style.display = 'none';
        errorListContainer.style.display = 'none';
        questionContainer.style.display = 'block';
        navPractice.classList.add('active');
        navError.classList.remove('active');
        loadQuestionBank(selectedExamFile);
    });

    // 加载题库
    async function loadQuestionBank(filePath) {
        try {
            const response = await fetch(filePath);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            currentQuestionBank = data.exam.questions;
            loadRandomQuestion(); // 加载题目后立即出题
        } catch (error) {
            console.error('加载题库失败:', error);
            questionContainer.innerHTML = `
                <div class="loading">
                    <p>加载题库失败，请检查 ${filePath} 文件是否存在且格式正确。</p>
                    <p>错误信息: ${error.message}</p>
                    <button class="btn btn-primary" style="margin-top: 20px;" onclick="location.reload()">返回重试</button>
                </div>
            `;
        }
    }

    // 随机获取一道题
    function getRandomQuestion() {
        if (!currentQuestionBank) return null;
        const randomIndex = Math.floor(Math.random() * currentQuestionBank.length);
        return currentQuestionBank[randomIndex];
    }

    // 渲染题目（省略，与之前一致）
    function renderSingleChoice(question) {
        const optionsHtml = question.options.map((option, index) => {
            const letter = String.fromCharCode(65 + index);
            return `
                <div class="option" data-letter="${letter}" data-index="${index}">
                    <span class="option-letter">${letter}</span>
                    ${option.substring(2)}
                </div>
            `;
        }).join('');
        return `
            <div class="question-stem">${question.stem}</div>
            <div class="options">${optionsHtml}</div>
            <div class="feedback" id="feedback"></div>
            <div class="ai-explanation" id="aiExplanation"></div>
        `;
    }

    function renderMultipleChoice(question) {
        const optionsHtml = question.options.map((option, index) => {
            const letter = String.fromCharCode(65 + index);
            return `
                <div class="option" data-letter="${letter}" data-index="${index}" data-multi="true">
                    <span class="option-letter">${letter}</span>
                    ${option.substring(2)}
                </div>
            `;
        }).join('');
        return `
            <div class="question-stem">${question.stem} <small>(多选题)</small></div>
            <div class="options">${optionsHtml}</div>
            <div class="action-btns">
                <button class="btn btn-outline" id="clearBtn">清空</button>
                <button class="btn btn-primary" id="submitBtn">提交答案</button>
            </div>
            <div class="feedback" id="feedback"></div>
            <div class="ai-explanation" id="aiExplanation"></div>
        `;
    }

    function renderTrueFalse(question) {
        return `
            <div class="question-stem">${question.stem}</div>
            <div class="options">
                <div class="option" data-answer="true">
                    <span class="option-letter">✓</span>
                    正确
                </div>
                <div class="option" data-answer="false">
                    <span class="option-letter">✗</span>
                    错误
                </div>
            </div>
            <div class="feedback" id="feedback"></div>
            <div class="ai-explanation" id="aiExplanation"></div>
        `;
    }

    function renderQuestion(question) {
        currentQuestion = question;
        selectedOptions = [];

        let questionHtml = '';
        switch (question.type) {
            case 'single_choice':
                questionHtml = renderSingleChoice(question);
                break;
            case 'multiple_choice':
                questionHtml = renderMultipleChoice(question);
                break;
            case 'true_false':
                questionHtml = renderTrueFalse(question);
                break;
            default:
                questionHtml = `<div class="question-stem">未知题型</div>`;
        }

        questionContainer.innerHTML = questionHtml;

        document.querySelectorAll('.option').forEach(option => {
            option.addEventListener('click', handleOptionClick);
        });

        const submitBtn = document.getElementById('submitBtn');
        const clearBtn = document.getElementById('clearBtn');

        if (submitBtn) {
            submitBtn.addEventListener('click', handleSubmit);
        }

        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                document.querySelectorAll('.option').forEach(opt => opt.classList.remove('selected'));
                selectedOptions = [];
            });
        }
    }

    // 处理选项点击（保持不变）
    function handleOptionClick(event) {
        const option = event.currentTarget;
        const isMultiChoice = option.hasAttribute('data-multi');

        if (!isMultiChoice) {
            document.querySelectorAll('.option').forEach(opt => { opt.style.pointerEvents = 'none'; });
            const feedbackElement = document.getElementById('feedback');
            const aiExplanationElement = document.getElementById('aiExplanation');
            let isCorrect = false;

            if (currentQuestion.type === 'true_false') {
                const userAnswer = option.getAttribute('data-answer') === 'true';
                isCorrect = userAnswer === currentQuestion.answer;
                option.classList.add(isCorrect ? 'correct' : 'incorrect');
            } else {
                const selectedLetter = option.getAttribute('data-letter');
                isCorrect = selectedLetter === currentQuestion.answer;
                option.classList.add(isCorrect ? 'correct' : 'incorrect');
                if (!isCorrect) {
                    document.querySelector(`.option[data-letter="${currentQuestion.answer}"]`).classList.add('correct');
                }
            }

            feedbackElement.textContent = isCorrect ? '回答正确！' : '回答错误！';
            feedbackElement.className = `feedback ${isCorrect ? 'correct' : 'incorrect'} show`;

            answeredCount++;
            if (isCorrect) correctCount++;
            answeredElement.textContent = answeredCount;
            correctElement.textContent = correctCount;
            accuracyElement.textContent = answeredCount > 0 ? `${Math.round((correctCount / answeredCount) * 100)}%` : '0%';

            if (isCorrect) {
                if (currentQuestion.isErrorPractice) {
                    markErrorCorrect(currentQuestion.stem);
                }
                setTimeout(() => loadRandomQuestion(), 1000);
            } else {
                addErrorQuestion(currentQuestion);
                aiExplanationElement.innerHTML = '<div class="loading">正在调用千问大模型解析...</div>';
                aiExplanationElement.style.display = 'block';
                getAIExplanation(currentQuestion).then(explanation => {
                    aiExplanationElement.innerHTML = `<h4>💡 AI解析</h4><p>${explanation}</p>`;
                }).catch(err => {
                    aiExplanationElement.innerHTML = `<h4>💡 AI解析</h4><p>获取AI解析失败：${err.message}</p>`;
                });

                const container = document.createElement('div');
                container.className = 'action-btns';
                container.innerHTML = `<button class="btn btn-primary" id="nextBtn">继续下一题</button>`;
                questionContainer.appendChild(container);
                document.getElementById('nextBtn').addEventListener('click', () => loadRandomQuestion());
            }
        } else {
            option.classList.toggle('selected');
            const letter = option.getAttribute('data-letter');
            const index = selectedOptions.indexOf(letter);
            if (index > -1) {
                selectedOptions.splice(index, 1);
            } else {
                selectedOptions.push(letter);
            }
        }
    }

    // 处理多选题提交（保持不变）
    function handleSubmit() {
        if (selectedOptions.length === 0) return;
        const feedbackElement = document.getElementById('feedback');
        const aiExplanationElement = document.getElementById('aiExplanation');
        const options = document.querySelectorAll('.option');
        let isCorrect = false;

        options.forEach(opt => { opt.style.pointerEvents = 'none'; });
        document.getElementById('submitBtn').disabled = true;
        document.getElementById('clearBtn').disabled = true;

        const userSelection = [...selectedOptions].sort();
        const correctAnswer = [...currentQuestion.answer].sort();
        isCorrect = JSON.stringify(userSelection) === JSON.stringify(correctAnswer);

        options.forEach(option => {
            const letter = option.getAttribute('data-letter');
            if (currentQuestion.answer.includes(letter)) {
                option.classList.add('correct');
            } else if (selectedOptions.includes(letter)) {
                option.classList.add('incorrect');
            }
        });

        feedbackElement.textContent = isCorrect ? '回答正确！' : '回答错误！';
        feedbackElement.className = `feedback ${isCorrect ? 'correct' : 'incorrect'} show`;

        answeredCount++;
        if (isCorrect) correctCount++;
        answeredElement.textContent = answeredCount;
        correctElement.textContent = correctCount;
        accuracyElement.textContent = answeredCount > 0 ? `${Math.round((correctCount / answeredCount) * 100)}%` : '0%';

        if (isCorrect) {
            if (currentQuestion.isErrorPractice) {
                markErrorCorrect(currentQuestion.stem);
            }
            setTimeout(() => loadRandomQuestion(), 1000);
        } else {
            addErrorQuestion(currentQuestion);
            aiExplanationElement.innerHTML = '<div class="loading">AI正在解析题目...</div>';
            aiExplanationElement.style.display = 'block';
            getAIExplanation(currentQuestion).then(explanation => {
                aiExplanationElement.innerHTML = `<h4>💡 AI解析</h4><p>${explanation}</p>`;
            }).catch(err => {
                aiExplanationElement.innerHTML = `<h4>💡 AI解析</h4><p>获取AI解析失败：${err.message}</p>`;
            });

            const container = document.createElement('div');
            container.className = 'action-btns';
            container.innerHTML = `<button class="btn btn-primary" id="nextBtn">继续下一题</button>`;
            questionContainer.appendChild(container);
            document.getElementById('nextBtn').addEventListener('click', () => loadRandomQuestion());
        }
    }

    // AI 解析（保持不变）
    async function getAIExplanation(question) {
        const key = genExplanationKey(question);
        const cache = localStorage.getItem('ai_explanations');
        let explanations = {};
        if (cache) {
            try {
                explanations = JSON.parse(cache);
            } catch (e) {}
        }
        if (explanations[key]) return explanations[key];

        const prompt = `你是一个大数据领域的资深专家和教育者。请以专业、清晰、易懂的方式解释以下题目：\n\n题目：${question.stem}\n\n${question.options ? `选项：\n${question.options.map(opt => `  - ${opt}`).join('\\n')}` : ''}\n\n正确答案：${Array.isArray(question.answer) ? question.answer.join(', ') : question.answer}\n\n请解释：\n这个问题的答案是什么？为什么是这个答案？`;

        try {
            const response = await fetch(API_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${API_KEY}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    model: 'qwen-turbo',
                    messages: [
                        { role: 'system', content: '你是一个专业的教育助手，擅长用清晰易懂且简练的的方式解释复杂的考试题目。问题解答不超过200字，且输出不要用md格式，以普通文本格式' },
                        { role: 'user', content: prompt }
                    ],
                    temperature: 0.7,
                    max_tokens: 1000
                })
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(`API请求失败: ${response.status} ${response.statusText}. ${errorData.error?.message || ''}`);
            }

            const data = await response.json();
            const explanation = data.choices[0].message.content.trim();
            explanations[key] = explanation;
            localStorage.setItem('ai_explanations', JSON.stringify(explanations));
            return explanation;
        } catch (error) {
            console.error('调用AI接口失败:', error);
            throw new Error(`AI解析服务调用失败: ${error.message}`);
        }
    }

    function genExplanationKey(question) {
        let key = question.stem + '||';
        if (Array.isArray(question.answer)) key += question.answer.join(',');
        else key += question.answer;
        if (question.options) key += '||' + question.options.join('||');
        return key;
    }

    // 加载随机题目
    function loadRandomQuestion() {
        if (!currentQuestionBank) {
            questionContainer.innerHTML = `
                <div class="loading">题库未加载，请返回选择题库。</div>
            `;
            return;
        }
        const randomQuestion = getRandomQuestion();
        if (loadingElement) loadingElement.style.display = 'none'; // 关键修复：隐藏 loading
        renderQuestion(randomQuestion);
    }

    // 页面初始化
    function init() {
        loadErrorQuestions();
        renderErrorList();

        navPractice.addEventListener('click', () => {
            selectContainer.style.display = 'none';
            errorListContainer.style.display = 'none';
            questionContainer.style.display = 'block';
            navPractice.classList.add('active');
            navError.classList.remove('active');

            if (currentQuestionBank) {
                loadRandomQuestion(); // 直接出题
            } else {
                window.location.reload()
                // questionContainer.innerHTML = '<div class="loading">请先开始练习以加载题库。</div>';
            }
        });

        navError.addEventListener('click', () => {
            selectContainer.style.display = 'none';
            questionContainer.style.display = 'none';
            errorListContainer.style.display = 'block';
            navPractice.classList.remove('active');
            navError.classList.add('active');
            renderErrorList();
        });
    }

    // 初始化
    init();
</script>
</body>
</html>
